<?php
/**
 * 提现表控制器
 */

namespace app\admin\controller;

use think\Request;
use app\common\model\UserDraw;
use app\common\model\UserAgent;

use app\common\validate\UserDrawValidate;
use think\Db;

class UserDrawController extends Controller
{
    //列表
    public function index(Request $request, UserDraw $model)
    {
        $param = $request->param();
        $model  = $model->scope('where', $param);
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['序号','站长ID','姓名','银行卡名','银行卡号','金额','状态','操作人','处理时间','创建时间','操作'];
            $body   = [];
            $data   = $model->select();
            foreach ($data as $item) {
                $record       = [];
                $record['id'] = $item->id;
                $record['uid'] = $item->uid;
                $record['amount'] = $item->amount;
                $record['bid'] = $item->bid;
                $record['username'] = $item->username;
                $record['bank_code'] = $item->bank_code;
                $record['note'] = $item->note;
                $record['status'] = $item->status_text;
                $record['adminuser'] = $item->adminuser;
                $record['dotime'] = $item->dotime;
                $record['create_time'] = $item->create_time;
                $record['delete_time'] = $item->delete_time;

                $body[]       = $record;
            }

            return $this->exportData($header, $body, 'user_draw-' . date('Y-m-d-H-i-s'));
        }

        $data = $model->paginate($this->admin['per_page'], false, ['query'=>$request->get()]);
        //关键词，排序等赋值
        $this->assign($request->get());

        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, UserDraw $model, UserDrawValidate $validate)
    {
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            
            $result = $model::create($param);

            $url = URL_BACK;
            if(isset($param['_create']) && $param['_create']==1){
               $url = URL_RELOAD;
            }

            return $result ? success('添加成功',$url) : error();
        }

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, UserDraw $model, UserDrawValidate $validate)
    {
        $data = $model::get($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            
            $result = $data->save($param);
            return $result ? success() : error();
        }

        $this->assign([
            'data' => $data,
        ]);
        return $this->fetch('add');
    }

    //删除
    public function del($id, UserDraw $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //提现审核
    public function auditDraw(Request $request, UserDraw $model)
    {
        $param = $request->param();
        if($request->isPost())
        {
            $radio = $param['radio'];
            $tid = $param['tid'];

            //查找该信息是否存在
            $t_info = UserDraw::find($tid);
            if(!$t_info)
            {
                return json(["errorCode"=>200,"msg"=>"该条数据异常，请刷新重试！"]);die;
            }

            //判断该条数据是否审核通过
            if($t_info['status']==1 || $t_info['status']==-1)
            {
                return json(["errorCode"=>200,"msg"=>"已审核,请不要重复审核！"]);die;
            }

            // 启动事务
            Db::startTrans();
            try{

                //查找站长信息
                $zid = $t_info['uid'];
                $zname = UserAgent::find($zid);
                //扣除站长的金额-已提现的金额
                $zMoney = $zname['user_money']-$t_info['amount'];

                if($radio==1)
                {
                    //审核成功
                    $auditData = [
                        'status'=>$radio,
                        'dotime'=>time()
                    ];

                    //平台流水记录
                    $dataUpdate = [
                        'amount'=>$t_info['amount'],
                        'note'=>"管理员已对站长".$zname['username']."提现金额为".$t_info['amount']."已审核通过",
                        'create_time'=>time(),
                    ];

                    //站长流水记录-通过
                    $zData = [
                        'uid'=>$zid,
                        'amount'=>$t_info['amount'],
                        'type'=>2,
                        'note'=>"站长".$zname['username']."提现金额为".$t_info['amount']."现金币余额为".$zMoney."元",
                        'create_time'=>time(),
                    ];

                    Db::table('user_agent')->where('id',$zid)->update(['user_money'=>$zMoney]);

                }else if($radio==-1){

                    //拒绝
                    $auditData = [
                        'status'=>$radio,
                        'dotime'=>time()
                    ];

                    //平台流水记录
                    $dataUpdate = [
                        'amount'=>$t_info['amount'],
                        'note'=>"管理员已对站长".$zname['username']."提现金额为".$t_info['amount']."已拒绝",
                        'create_time'=>time(),
                    ];

                    //站长流水记录-拒绝
                    $zData = [
                        'uid'=>$zid,
                        'amount'=>$t_info['amount'],
                        'type'=>2,
                        'note'=>"站长".$zname['username']."提现金额为".$t_info['amount']."现金币余额为".$zMoney."元,已被管理员拒绝;如有疑问请联系平台！",
                        'create_time'=>time(),
                    ];
                }

                Db::table('user_draw')->where('id',$tid)->update($auditData);
                Db::table('admin_money_record')->insert($dataUpdate);
                Db::table('user_money_record')->insert($zData);

                // 提交事务
                Db::commit();
                return json(["errorCode"=>200,"msg"=>"恭喜，审核成功！"]);die;
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(["errorCode"=>200,"msg"=>"抱歉，审核失败！"]);die;
            }
        }
    }

    
}
